package cn.iocoder.yudao.module.erp.controller.admin.secaccount;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.module.erp.controller.admin.stock.vo.check.ErpStockCheckRespVO;
import cn.iocoder.yudao.module.system.dal.dataobject.dept.DeptDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import org.springframework.web.bind.annotation.*;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import jakarta.validation.constraints.*;
import jakarta.validation.*;
import jakarta.servlet.http.*;

import java.util.*;
import java.io.IOException;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;

import cn.iocoder.yudao.module.erp.controller.admin.secaccount.vo.*;
import cn.iocoder.yudao.module.erp.dal.dataobject.secaccount.SecAccountDO;
import cn.iocoder.yudao.module.erp.service.secaccount.SecAccountService;

@Tag(name = "管理后台 - ERP 二级库台账")
@RestController
@RequestMapping("/erp/sec-account")
@Validated
public class SecAccountController {

    @Resource
    private SecAccountService secAccountService;

    @PostMapping("/create")
    @Operation(summary = "创建ERP 二级库台账")
    @PreAuthorize("@ss.hasPermission('erp:sec-account:create')")
    public CommonResult<Long> createSecAccount(@Valid @RequestBody SecAccountSaveReqVO createReqVO) {
        return success(secAccountService.createSecAccount(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新ERP 二级库台账")
    @PreAuthorize("@ss.hasPermission('erp:sec-account:update')")
    public CommonResult<Boolean> updateSecAccount(@Valid @RequestBody SecAccountSaveReqVO updateReqVO) {
        secAccountService.updateSecAccount(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除ERP 二级库台账")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('erp:sec-account:delete')")
    public CommonResult<Boolean> deleteSecAccount(@RequestParam("id") Long id) {
        secAccountService.deleteSecAccount(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得ERP 二级库台账")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('erp:sec-account:query')")
    public CommonResult<SecAccountRespVO> getSecAccount(@RequestParam("id") Long id) {
        SecAccountDO secAccount = secAccountService.getSecAccount(id);
        return success(BeanUtils.toBean(secAccount, SecAccountRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得ERP 二级库台账分页")
    @PreAuthorize("@ss.hasPermission('erp:sec-account:query')")
    public CommonResult<PageResult<SecAccountRespVO>> getSecAccountPage(@Valid SecAccountPageReqVO pageReqVO) {
        PageResult<SecAccountDO> pageResult = secAccountService.getSecAccountPage(pageReqVO);
        if (pageResult != null) {
            Set<Long> deptIds = new HashSet<>();
            Set<Long> toDeptIds = new HashSet<>();
            Set<Long> fromDeptIds = new HashSet<>();
            Map<Long, String> toDeptNameMap = new HashMap<>();
            Map<Long, String> deptNameMap = new HashMap<>();
            Map<Long, String> fromDeptNameMap = new HashMap<>();
            Map<String, String> creatorUsernameMap = new HashMap<>();
            Set<String> creatorIds = new HashSet<>();
            for (SecAccountDO secAccountDO : pageResult.getList()) {
                creatorIds.add(secAccountDO.getCreator());
            }
            if (CollUtil.isNotEmpty(creatorIds)) {
                List<AdminUserDO> userList = secAccountService.selectUserListByIds(creatorIds);
                for (AdminUserDO adminUserDO : userList) {
                    creatorUsernameMap.put(String.valueOf(adminUserDO.getId()), adminUserDO.getNickname());
                }
            }
            //如果没有数据，直接返回
            if (pageResult.getTotal() != 0) {
                //循环查询翻译部门
                for (SecAccountDO secAccountDO : pageResult.getList()) {
                    deptIds.add(secAccountDO.getDeptId());
                    toDeptIds.add(secAccountDO.getToDeptId());
                    fromDeptIds.add(secAccountDO.getFromDeptId());
                }
                List<DeptDO> deptList = secAccountService.selectDeptByIds(deptIds);
                List<DeptDO> toDeptList = secAccountService.selectDeptByIds(toDeptIds);
                List<DeptDO> fromDeptList = secAccountService.selectDeptByIds(fromDeptIds);
                for (DeptDO deptDO : deptList) {
                    deptNameMap.put(deptDO.getId(), deptDO.getName());
                }
                for (DeptDO deptDO : toDeptList) {
                    toDeptNameMap.put(deptDO.getId(), deptDO.getName());
                }
                for (DeptDO deptDO : fromDeptList) {
                    fromDeptNameMap.put(deptDO.getId(), deptDO.getName());
                }
                PageResult<SecAccountRespVO> pageResult1 = BeanUtils.toBean(pageResult, SecAccountRespVO.class);
                for (SecAccountRespVO secAccountRespVO : pageResult1.getList()) {
                    secAccountRespVO.setDeptName(deptNameMap.get(secAccountRespVO.getDeptId()));
                    secAccountRespVO.setToDeptName(toDeptNameMap.get(secAccountRespVO.getToDeptId()));
                    secAccountRespVO.setFromDeptName(fromDeptNameMap.get(secAccountRespVO.getFromDeptId()));
                    secAccountRespVO.setCreatorName(creatorUsernameMap.get(secAccountRespVO.getCreator()));
                }
                return success(pageResult1);
            }
        }
        return success(BeanUtils.toBean(pageResult, SecAccountRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出ERP 二级库台账 Excel")
    @PreAuthorize("@ss.hasPermission('erp:sec-account:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportSecAccountExcel(@Valid SecAccountPageReqVO pageReqVO,
                                      HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<SecAccountDO> list = secAccountService.getSecAccountPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "ERP 二级库台账.xls", "数据", SecAccountRespVO.class,
                BeanUtils.toBean(list, SecAccountRespVO.class));
    }

}